<?php

namespace StarCloud\Library\Sdk;

use Framework\DiServices\HttpClient;
use Phalcon\Di;
use StarCloud\Library\Exception;

class BaiduWpApi
{
    /* @var $httpClient HttpClient */
    private $httpClient;
    private $cacheClass;
    private $secretKey = 'QJNADfPj5YPmjzRS';
    private $uk = 3653629551;

    private $oauthConfig = [
        'appId' => '116358179',
        'appKey' => 'ZS4WMmo8QLnS27biBLAmfMel6zkbOLP5',
        'appSecret' => '9NwCGOj4xgvqX5a4PINZUpGH2oZ4f008',
        'callback' => 'https://api.doumvip.com/api/bdwp/callback'
    ];

    public function __construct($config = [])
    {
        $this->httpClient = Di::getDefault()->get('httpClient');
        $this->cacheClass = Di::getDefault()->get('redis');
    }

    public function sendVip($userUk, $scene = 1)
    {
        if (time() < strtotime('2025-01-07')) {
            throw new Exception(9999, "2025-01-07 零点后才投入生产使用");
        }
        $url = "https://pan.baidu.com/rest/2.0/xpan/fx/acquisition?";

        $body = [
            'method' => 'reportuser',
            'bussid' => 10,
            'provider_uk' => $this->uk,
            'uk' => intval($userUk),
            'scene' => $scene,
        ];

        $body['sign'] = $this->sign($body);

        $url .= http_build_query($body);

        $response = $this->httpClient->sendGetRequest($url, $body);


        $json = json_decode($response->getBody()->getContents(), true);

        Di::getDefault()->get('logger')->info("bdwp_vip:" . json_encode($json) . ' url ' . $url);


        if (isset($json['errno']) && $json['errno'] == 0) {
            return true;
        }

        throw new Exception(9999, $json['show_msg'] ?? "系统错误");
    }

    public function getOauthConfig($uid)
    {
        $callback = $this->oauthConfig['callback'];
        $callback = urlencode($callback);
        $url = "https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id={$this->oauthConfig['appKey']}&redirect_uri={$callback}&scope=basic,netdisk&device_id={$this->oauthConfig['appId']}&display=mobile&state={$uid}";
        return [
            'access_token' => $this->getAccessToken(),
            'url' =>  $url,
        ];
    }

    public function getOauthAccessToken()
    {
        $callback = $this->oauthConfig['callback'];
        $callback = urlencode($callback);
        $url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code={$_GET['code']}&client_id={$this->oauthConfig['appKey']}&client_secret={$this->oauthConfig['appSecret']}&redirect_uri=$callback";

        $response = $this->httpClient->sendGetRequest($url);

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['access_token'])) {
            $this->setAccessTokenKey($json['access_token']);
        }

        return $json;
    }

    public function createLinkCode($link)
    {
        $accessToken = $this->getAccessToken();

        $url = "https://pan.baidu.com/rest/2.0/xpan/third?";

        $body = [
            'method' => 'commandset',
            'access_token' => $accessToken,
            'url' => $link,
            'time' => time()
        ];

        $url .= http_build_query($body);

        $response = $this->httpClient->sendPostRequest($url, $body);
        $json = $response->getBody()->getContents();
        $json = json_decode($json, true);
        if (isset($json['errno'])) {
            if ($json['errno'] == 0) {
                return $json['data']['command_word'];
            } else {
                throw new Exception(9999, empty($json['errmsg']) ? "链接错误" : $json['errmsg']);
            }
        } else {
            throw new Exception(9999, $json['errmsg'] ?? "链接错误");
        }
    }

    public function getAccessTokenKey()
    {
        return "baidu_oauth_access_token";
    }

    public function getAccessToken()
    {
        return $this->cacheClass->get($this->getAccessTokenKey());
    }

    public function setAccessTokenKey($key)
    {
        $this->cacheClass->set($this->getAccessTokenKey(), $key, 86400 * 25);
    }

    public function sign($params)
    {
        unset($params['method']);

        foreach ($params as &$item) {
            $item = strval($item);
        }
        $str = '';
        $arr = str_split(json_encode($params));
        sort($arr);
        foreach ($arr as $k => $v) {
            $str .= $v;
        }
        $str .= $this->secretKey;
        return hash('sha256', $str);
    }

    public function queryIncome($setDay, $page = 1, $limit = 100)
    {
        $url = "https://pan.baidu.com/rest/2.0/xpan/fx/acquisition?";

        $body = [
            'method' => 'income',
            'bussid' => 10,
            'fxuk' => $this->uk,
            'settle_day' => strtotime($setDay),
            'page' => $page,
            'limit' => $limit,
        ];

        $body['sign'] = $this->sign($body);

        $url .= http_build_query($body);

        $response = $this->httpClient->sendGetRequest($url, $body);

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['data'])) {
            return $json['data'];
        }
        return null;
    }

    public function queryUk($uk = 4018457656)
    {
        $url = "https://pan.baidu.com/rest/2.0/xpan/fx/acquisition?";

        $body = [
            'method' => 'relation',
            'bussid' => 10,
            'fxuk' => $this->uk,
            'uk' => $uk,
            'page' => 1,
            'limit' => 1,
        ];

        $body['sign'] = $this->sign($body);

        $url .= http_build_query($body);

        $response = $this->httpClient->sendGetRequest($url, $body);

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['data']['list'][0])) {
            return $json['data']['list'][0];
        }

        if (isset($json['errno']) && $json['errno'] == '900402') {
            throw new Exception(9999, '你的账号已在别家平台签约过， 请重新换账号签约报备');
        }

        if (isset($json['errno']) && $json['errno'] == '900403') {
            throw new Exception(9999, '你的账号还未签约， 先签约再报备');
        }

        return false;
    }
}